(function() {
    'uses strict';

    /**
     * 用户必须在微信中使用
     * @type {[type]}
     * (/micromessenger/.test(ua))
     */
    var ua = navigator.userAgent.toLowerCase();
    if (!/micromessenger/.test(ua)) {
        console.warn("请您在微信中打开该链接，谢谢！");
        alert("请您在微信中打开该链接，谢谢！");
        return;
    }
    angular.module('weApp', ['ionic', 'LocalStorageModule', 'pasvaz.bindonce', 'weApp.services', 'weApp.controllers', 'weApp.directives'])

            .run(['$rootScope', '$state', '$stateParams', '$ionicPlatform', '$http', 'weAppDataBase', 'localStorageService', '$ionicLoading', 'checkUserPosition', '$q', '$ionicPopup',
                function($rootScope, $state, $stateParams, $ionicPlatform, $http, weAppDataBase, localStorageService, $ionicLoading, checkUserPosition, $q, $ionicPopup) {


                    $rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
                        $rootScope.prevState = fromState;
                        $rootScope.prevParams = fromParams;
                        $rootScope.currUrl = toState;
                    });

                    //远程服务器地址
                    //延安
                    /*$rootScope.rootLocation = "http://117.34.118.16:8789/bi";
                     $rootScope.rootAbsoluteUrl = "http://www.16bus.net/wechat";
                     $rootScope.cityCode = "284";
                     $rootScope.cityName = "延安";
                     $rootScope.cityLocation = {
                     lat: "36.591169",
                     lng: "109.495702"
                     };
                     $rootScope.systemName = "易公交";*/
                    // 江门
                    $rootScope.rootLocation = "http://219.130.135.52:8789/bi";
                    $rootScope.rootAbsoluteUrl = "http://mobile.jmqyjt.com/wechat";
                    $rootScope.cityCode = "302";
                    $rootScope.cityName = "江门";
                    $rootScope.cityLocation = {
                        lat: "22.584404",
                        lng: "113.088161"
                    };
                    $rootScope.systemName = "江门智能公交";

                    $rootScope.refreshPerSec = 6500;

                    $rootScope.appReadyPromise = $q.defer();

                    $rootScope.cityNotIn = localStorageService.get("cityNotIn");

                    $rootScope.locationURI = encodeURIComponent(location.href.split('#')[0]);

                    $rootScope.tabs = [
                        {
                            "name": "首页",
                            "herf": "index",
                            "icon": "we-icon-home"
                        }, 
                        {
                            "name": "换乘",
                            "herf": "trans",
                            "icon": "we-icon-huanyihuan"
                        }, 
                        {
                            "name": "收藏",
                            "herf": "favor",
                            "icon": "we-icon-favor"
                        },
                        {
                            "name": "更多",
                            "herf": "more",
                            "icon": "we-icon-more"
                        }
                    ];

                    $rootScope.myAddress = null;
                    $rootScope.siteTimes = null;

                    /**
                     * 微信对接配置
                     */
                    /**
                     * 本地请求微信服务器配置
                     * appId/timestamp/nonceStr/signature
                     */
                    var rootReq = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/wechat/accesstoken/sign',
                        data: {
                            "tokenUrl": $rootScope.locationURI,
                            "cityCode": $rootScope.cityCode
                        }
                    };

                    $http(rootReq)
                            .then(function(wxRegRes) {

                                var wxConfig = wxRegRes.data.data;

                                wx.config({
                                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                    appId: wxConfig.appid, // 必填，公众号的唯一标识
                                    timestamp: wxConfig.timestamp, // 必填，生成签名的时间戳
                                    nonceStr: wxConfig.noncestr, // 必填，生成签名的随机串
                                    signature: wxConfig.signature, // 必填，签名，见附录1
                                    jsApiList: ['getLocation', 'hideAllNonBaseMenuItem', 'showMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                });
                                /**
                                 * 微信配置成功后调用 获取用户地理位置接口
                                 * 该接口返回的为GPS经纬度信息，需要在回调函数中调用百度接口进行经纬度信息转换
                                 */
                                wx.ready(function() {

                                    /**
                                     * 微信中获取用户地理位置信息
                                     */
                                    wx.getLocation({
                                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                                        success: function(getLocationRes) {
                                            // console.log(getLocationRes);
                                            //百度转换GPS坐标至百度坐标API
                                            var transformPosUrl = "http://api.map.baidu.com/geoconv/v1/?coords=" + getLocationRes.longitude + "," + getLocationRes.latitude + "&callback=JSON_CALLBACK&from=1&to=5&ak=7vVOlMOKr03PaWX82WajF6mG";

                                            $http.jsonp(transformPosUrl)
                                                    .then(function(bdRes) {
                                                        // console.log( bdRes );
                                                        /**
                                                         * 根据算法判断是否在目标城市内
                                                         * 判断依据为指定坐标为圆心的30公里范围内
                                                         */
                                                        var isIn = checkUserPosition.getDistance($rootScope.cityLocation.lat, $rootScope.cityLocation.lng, bdRes.data.result[0].y, bdRes.data.result[0].x) < 30 ? true : false;

                                                        // alert("是否在城市范围内:" + isIn );

                                                        $rootScope.userLocation = {
                                                            latitude: isIn ? (bdRes.data.result[0].y).toString() : $rootScope.cityLocation.lat,
                                                            longitude: isIn ? (bdRes.data.result[0].x).toString() : $rootScope.cityLocation.lng
                                                        };
                                                        // console.log($rootScope.userLocation);
                                                        // 113.119092,22.56342
                                                        // $rootScope.userLocation = {
                                                        //     latitude : "36.571278218682",
                                                        //     longitude: "109.48809913015"
                                                        // };

                                                        if (!isIn && $rootScope.cityNotIn !== "viewed") {

                                                            var alertPopup = $ionicPopup.alert({
                                                                title: '提示',
                                                                template: '您所在的城市尚未开通 ' + $rootScope.systemName + ' 服务，系统将自动切换至' + $rootScope.cityName + '市',
                                                                okText: "我知道了",
                                                                okType: "button-balanced"
                                                            });
                                                            alertPopup.then(function() {
                                                                localStorageService.set("cityNotIn", "viewed");
                                                            });

                                                        }
                                                        /*$rootScope.cityLocation = {
                                                         lat: "36.601492",
                                                         lng: "109.495103"
                                                         };*/
                                                        var lng = null;
                                                        var lat = null;
                                                        if (!isIn) {
                                                            lat = $rootScope.cityLocation.lat;
                                                            lng = $rootScope.cityLocation.lng;
                                                        } else {
                                                            lat = bdRes.data.result[0].y;
                                                            lng = bdRes.data.result[0].x;
                                                        }
                                                        // alert("纬度" + bdRes.data.result[0].y + ";" + "经度" + bdRes.data.result[0].x  );

                                                        var getCityfromePos = "http://api.map.baidu.com/geocoder/v2/?ak=7vVOlMOKr03PaWX82WajF6mG&location=" + lat + "," + lng + "&callback=JSON_CALLBACK&output=json";

                                                        $http.jsonp(getCityfromePos)
                                                                .then(function(cityPos) {
                                                                    // alert("当前详细地址:" + cityPos.data.result.formatted_address );

                                                                    $rootScope.userLocation.nowCity = cityPos.data.result.addressComponent.city;
                                                                    $rootScope.userLocation.nowAddress = cityPos.data.result.formatted_address;
                                                                    $rootScope.myAddress = {
                                                                        name: cityPos.data.result.formatted_address,
                                                                        location: {
                                                                            lat: lat,
                                                                            lng: lng
                                                                        }
                                                                    }
                                                                    localStorageService.set("myAddress", JSON.stringify($rootScope.myAddress));
                                                                    // console.log( $rootScope.userLocation );
                                                                    // alert( $rootScope.userLocation.nowAddress );

                                                                    //返回所有查询结束后的成功消息Promise
                                                                    //告诉后续代码前期工作已准备完毕
                                                                    $rootScope.appReadyPromise.resolve("finished");

                                                                }, function(error) {
                                                                    $rootScope.appReadyPromise.reject(error);
                                                                });


                                                    });

                                        }
                                    });

                                    /**
                                     * 微信中隐藏所有非基础类按钮
                                     */
                                    wx.hideAllNonBaseMenuItem();

                                    /**
                                     * 微信中批量显示指定按钮
                                     * @type {Array}
                                     */
                                    wx.showMenuItems({
                                        menuList: [
                                            "menuItem:share:appMessage", //分享给朋友
                                            "menuItem:share:timeline", //分享到朋友圈
                                            "menuItem:favorite" //收藏
                                        ]
                                    });

                                    wx.onMenuShareAppMessage({
                                        title: $rootScope.systemName, // 分享标题
                                        desc: '实时掌握附近站点与车辆预测到站信息', // 分享描述
                                        link: $rootScope.rootAbsoluteUrl, // 分享链接
                                        imgUrl: $rootScope.rootAbsoluteUrl + '/img/share-logo.png', // 分享图标
                                        success: function() {
                                            /*var sharePop = $ionicPopup.alert({
                                             title: '提示',
                                             template: '成功分享给朋友！',
                                             okText: "确定",
                                             okType: "button-balanced"
                                             });*/

                                        },
                                        cancel: function() {
                                            // 用户取消分享后执行的回调函数
                                        }
                                    });

                                    wx.onMenuShareTimeline({
                                        title: $rootScope.systemName, // 分享标题
                                        link: $rootScope.rootAbsoluteUrl, // 分享链接
                                        imgUrl: $rootScope.rootAbsoluteUrl + '/img/share-logo.png', // 分享图标
                                        success: function() {
                                            // 用户确认分享后执行的回调函数
                                            var sharePop = $ionicPopup.alert({
                                                title: '提示',
                                                template: '成功分享到朋友圈！',
                                                okText: "确定",
                                                okType: "button-balanced"
                                            });
                                        },
                                        cancel: function() {
                                            // 用户取消分享后执行的回调函数
                                        }
                                    });

                                });

                                wx.error(function(error) {
                                    console.warn(error);
                                    alert("微信服务获取出错，请与管理员联系.");
                                });

                                //移除数据表
                                // weAppDataBase.dropDB();

                                /**
                                 * 使用WebSQL创建一个stations database
                                 */
                                weAppDataBase.createDB();


                                // weAppDataBase.deleteDB().then(function(res){
                                //   localStorageService.set("initStationLineDb", null);
                                // });

                                /**
                                 * 如果没有插入原始数据，则请求服务器后将原始数据插入WebSQL中。使用LocalStorage进行标识
                                 * @param  {[type]} localStorageService.get("initStationLineDb") !             [description]
                                 * @return {[type]}                                              [description]
                                 */

                                if (localStorageService.get("initStationLineDb") !== "created") {
                                    $ionicLoading.show({
                                        template: '正在初始化数据...'
                                    });
                                    var req = {
                                        method: 'post',
                                        url: $rootScope.rootLocation + '/line/station/update',
                                        data: {
                                            "cityCode": $rootScope.cityCode,
                                            "cityName": $rootScope.cityName
                                        }
                                    };

                                    $http(req)
                                            .then(function(result) {
                                                $ionicLoading.show({
                                                    template: '开始插入数据...'
                                                });
                                                var stations = result.data.data.lineStations;

                                                if (stations.length) {
                                                    for (var i = 0; i < stations.length; i++) {
                                                        var thisStation = stations[i];
                                                        weAppDataBase.insert(thisStation.lineId, thisStation.lineName, thisStation.cityMapCode, thisStation.cityName);
                                                    }
                                                    localStorageService.set("initStationLineDb", "created");
                                                }
                                                ;
                                                $ionicLoading.hide();
                                            })

                                }


                            });

                    return $rootScope.appReadyPromise.promise;

                    // $ionicPlatform.ready(function() {
                    //   // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                    //   // for form inputs)
                    //   if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                    //     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    //     cordova.plugins.Keyboard.disableScroll(true);

                    //   }
                    //   if (window.StatusBar) {
                    //     // org.apache.cordova.statusbar required
                    //     StatusBar.styleDefault();
                    //   }
                    // });

                }])

            .config(['$ionicConfigProvider', '$stateProvider', '$urlRouterProvider', 'localStorageServiceProvider', '$httpProvider',
                function($ionicConfigProvider, $stateProvider, $urlRouterProvider, localStorageServiceProvider, $httpProvider) {

                    // if(!ionic.Platform.isIOS()) $ionicConfigProvider.scrolling.jsScrolling(false);

                    localStorageServiceProvider.setPrefix('zhxWeApp');

                    $httpProvider.interceptors.push('requestInerceptor');

                    $stateProvider

                            .state('index', {
                                url: '/index',
                                templateUrl: 'templates/tab-dash.html',
                                controller: 'DashCtrl',
                                cache: false
                            })
                            .state('search', {
                                url: '/search',
                                templateUrl: 'templates/search.html',
                                controller: 'searchCtrl',
                                cache: false
                            })
                            .state('searchRes', {
                                url: '/search-result/',
                                templateUrl: 'templates/search-result.html',
                                controller: 'searchResCtrl',
                                cache: false,
                                params: {
                                    searchText: null
                                }
                            })
                            .state('station', {
                                url: '/station',
                                templateUrl: 'templates/station.html',
                                controller: 'stationCtrl',
                                cache: false
                            })
                            .state('line', {
                                url: '/line',
                                templateUrl: 'templates/line.html',
                                controller: 'lineCtrl',
                                cache: false,
                                params: {
                                    searchText: null
                                }
                            })
                            .state('favor', {
                                url: '/favor',
                                templateUrl: "templates/favor.html",
                                controller: "favorCtrl",
                                cache: false
                            })
                            .state('trans', {
                                url: '/trans',
                                templateUrl: "templates/trans.html",
                                controller: "transCtrl",
                                cache: false,
                                params: {
                                    data: null
                                }
                            })
                            .state('location', {
                                url: '/location',
                                templateUrl: "templates/location.html",
                                controller: "locationCtrl",
                                cache: false,
                                params: {
                                    tit: null,
                                    tag: null
                                }
                            })
                            .state('map', {
                                url: '/map',
                                templateUrl: "templates/map.html",
                                controller: "mapCtrl",
                                cache: false,
                                params: {
                                    tit: null,
                                    tag: null
                                }
                            })
                            .state('transfer', {
                                url: '/transfer',
                                templateUrl: "templates/transfer.html",
                                controller: "transferCtrl",
                                cache: false,
                                params: {
                                    data: null
                                }
                            })
                            .state('more', {
                                url: '/more',
                                templateUrl: "templates/more.html",
                                cache: false
                            })
                            .state('assess', {
                                url: '/assess',
                                templateUrl: "templates/assess.html",
                                controller: "assessCtrl",
                                cache: false
                            })
                            .state('about', {
                                url: '/about',
                                templateUrl: "templates/about.html",
                                cache: false
                            })
                            .state('help', {
                                url: '/help',
                                templateUrl: "templates/help.html",
                                controller: "helpCtrl",
                                cache: false
                            })
                            .state('question', {
                                url: '/question',
                                templateUrl: "templates/question.html",
                                controller: "questionCtrl",
                                cache: false
                            })
                            .state('board', {
                                url: '/board',
                                templateUrl: "templates/board.html",
                                controller: "boardCtrl",
                                cache: false
                            })
                            .state('helpContent', {
                                url: '/helpContent',
                                templateUrl: "templates/helpContent.html",
                                controller: "helpContentCtrl",
                                cache: false
                            })
                            .state('boardContent', {
                                url: '/boardContent',
                                templateUrl: "templates/boardContent.html",
                                controller: "boardContentCtrl",
                                cache: false
                            });


                    // if none of the above states are matched, use this as the fallback
                    $urlRouterProvider.otherwise('/trans');

                }]);

    // wx.ready(function(){
    //   wx.getLocation({
    //     type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    //     success: function (res) {
    //       console.log( res );
    //         var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
    //         var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
    //         var speed = res.speed; // 速度，以米/每秒计
    //         var accuracy = res.accuracy; // 位置精度
    //     }
    //   })
    // });

    /**
     * common js
     * Designed by vicco
     * 2015-10-09
     */
    /**
     * JAVASCRIPT 全局数组对象新增 indexOf 和 remove 两个方法
     * 用来移除数组中指定值（非下标）
     */
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val)
                return i;
        }
        return -1;
    };
    Array.prototype.remove = function(val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    //去除字符串所有空格
    String.prototype.trimSpace = function() {
        return this.replace(/\s+/g, "");
    };

})();